package com.yimi.yinhepda.db.dao;

import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.yimi.yinhepda.base.BaseApplication;
import com.yimi.yinhepda.db.helper.DbHelperUC;
import com.yimi.yinhepda.db.table.BillRouteTable;

import java.sql.SQLException;

/**
 * @author lj
 * 快递错分错发路由信息表操作
 */

public class BillRouteTableDao extends BaseDaoUC<BillRouteTable, Long> {

    public BillRouteTableDao() {
        super(DbHelperUC.getInstance(BaseApplication.getContext()), BillRouteTable.class);
    }

    public BillRouteTable findDataByBillCode(String billCode) {
        try {
            QueryBuilder<BillRouteTable, Long> queryBuilder = dao.queryBuilder();
            BillRouteTable billRouteTable = queryBuilder.where()
                    .eq("bill_code", billCode)
                    .queryForFirst();
            return billRouteTable;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除7前天的路由信息
     */
    public void deleteDataBefore7Day() {
        try {
            DeleteBuilder<BillRouteTable, Long> deleteBuilder = dao.deleteBuilder();
            deleteBuilder.where().lt("update_time", System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000);
            deleteBuilder.delete();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断表是否存在
     *
     * @param tableName 表名
     * @return true存在
     */
    public boolean tableIsExist(String tableName) {
        SQLiteDatabase db = getDbHelper().getWritableDatabase();
        boolean result = false;
        if (tableName == null) {
            return false;
        }
        Cursor cursor = null;
        try {
            String sql = "select count(*) as c from Sqlite_master  where type ='table' and name ='" + tableName.trim() + "' ";
            cursor = db.rawQuery(sql, null);
            if (cursor.moveToNext()) {
                int count = cursor.getInt(0);
                if (count > 0) {
                    result = true;
                }
            }
        } catch (Exception e) {
            // TODO: handle exception
        }
        finally {
            if (cursor!=null){
               cursor.close();
            }
        }
        return result;
    }
}
